package com.lmx.cloud;

import java.util.Date;
import java.util.Queue;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.text.SimpleDateFormat;
import com.lmx.bean.FileUnit;
import io.minio.MinioClient;

import io.minio.errors.InvalidEndpointException;
import io.minio.errors.InvalidPortException;
import com.lmx.creceive.*;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;

import java.io.InputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

// 真正的文件上传模块，调用upload就直接上传
public class FileUploader {
  private static int index = 0;
  private static ExecutorService threadPool = Executors.newFixedThreadPool(1);
  private static MinioClient client;
  public static String bucket = "hitwholderdata";
  //udp
  public static DatagramSocket datagramSocket;
  public static int lastPos;
  public static int Pos;
  public static int speed;
  // public static String bucket = "hitwhtest";
  

  private static void init() throws InvalidEndpointException, InvalidPortException {
    client = new Client();
  }
  public static void upload(FileUnit fileUnit) throws Exception {

    if (client == null) {
      init();
    }

    boolean isExist = client.bucketExists(bucket);
    if (!isExist) {
      client.makeBucket(bucket);

    }
    // LOG.info("[+] Start upload file "+fileUnit.getFile().getName() +" topic:
    // "+fileUnit.getTopic());
    client.putObject(bucket, fileUnit.getPath(), fileUnit.getFile().getAbsolutePath());
    deletefile(fileUnit);
    // LOG.info("[+] File "+fileUnit.getFile().getName()+" uploaded, delete file.");
    // movetouploaded(fileUnit);
  }
  public static void InitUpload() throws IOException
  {
      datagramSocket = new DatagramSocket(9998);
  }
  public static void upload(int[] x) throws Exception {

    // int[] x=myReceive.canreceive();
    // datagramSocket = new DatagramSocket(9998);
    // int[] x={1,2,3,20,5,6,7,8,9,10,11,12,25};
    System.out.println("java1 end");
      try{
        if (client == null) {
          init();
        }
        boolean isExist = client.bucketExists(bucket);
        if (!isExist) {
          client.makeBucket(bucket);
          
        }
      }catch(Exception e){
        try{
          Thread.sleep(1000);
        }catch(InterruptedException e1){
          e1.printStackTrace();
        }
      }
      speed=x[3];
      lastPos=Pos;
      Pos=x[12];
      String data1=null;
      String data2=null;
      System.out.println("java2 start");
      boolean t1=false;
      boolean t2=false;
      while(true)
      {
        //传输
        byte[] container = new byte[1024];
        DatagramPacket datagramPacket = new DatagramPacket(container,0,container.length);
        datagramSocket.receive(datagramPacket);//阻塞式接收

        //断开连接
        byte[] datas = datagramPacket.getData();
        String data = new String(datas, 0, datagramPacket.getLength(), StandardCharsets.UTF_8);
        System.out.println(data);
        // 上传到云
        int pos;
        
        pos=data.indexOf("openface",0);
        if(pos!=-1)
        {
          t1=true;
          pos=data.indexOf(":", pos);
          data1=data.substring(pos+1, data.length());
        }
        else
        {
          t2=true;
          pos=data.indexOf(":", pos);
          data2=data.substring(pos+1, data.length());
        }
        if(t1&&t2)
        {
          t1=false;
          t2=false;
          break;
        }
      }
      //面部疲劳等级和加速度
      double grade=0.0;
      double accl=Double.parseDouble(data2);
      double faceGrade=Double.parseDouble(data1);
      grade+=accl+faceGrade;
      if(Pos>lastPos)
        grade+=0.2;
      if(speed<60)
      {
        grade*=1.0;
      }
      else if(speed<70)
        grade*=1.1;
      else if(speed<80)
        grade*=1.2;
      else if(speed<90)
        grade*=1.3;
      else if(speed<100)
        grade*=1.4;
      else if(speed<110)
        grade*=1.5;
      else if(speed<120)
        grade*=1.6;
      else if(speed<130)
        grade*=1.7;
      else if(speed<140)
        grade*=1.8;
      else
        grade*=2.0;

      // 上传数据
      String str=String.valueOf(grade);
          
      Date date = new Date();
      SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
      String date1 = formatter.format(date);
      // System.out.println(date1);
      InputStream is = new ByteArrayInputStream(str.getBytes());
      String objectname = "distributed/can1/" + date1 + "-" +(index++)+ ".txt";
      try {
        client.putObject(bucket, objectname,
            is, str.length(), "text/plain");
        // queue.poll();
      } catch (Exception e) {
        // TODO Auto-generated catch block
        
        e.printStackTrace();
      }
            // is.close();

    // int []x={1,2};
    // while(true)
    // {
    //   // System.out.println("java1 end");
    //   try{
    //     if (client == null) {
    //       init();
    //     }
    //     boolean isExist = client.bucketExists(bucket);
    //     if (!isExist) {
    //       client.makeBucket(bucket);
    
    //     }
    //   }catch(Exception e){
    //     try{
    //       Thread.sleep(1000);
    //     }catch(InterruptedException e1){
    //       e1.printStackTrace();
    //     }
    //   }
      // while(!queue.isEmpty()) {
      //   System.out.println("java2 end");
      //   int[] x = queue.poll();
      //   // System.out.println(x);
      //   threadPool.submit(new Runnable() {
      //     @Override
      //     public void run() {
      //       // TODO Auto-generated method stub
      //       StringBuffer ss = new StringBuffer();
      //       // TODO Auto-generated method stub
      //       for (int i = 0; i < x.length; ++i) {
      //         ss.append(x[i]);
      //         ss.append(" ");
      //       }
      //       String str = ss.toString();
      //       Date date = new Date();
      //       SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      //       String date1 = formatter.format(date);
      //       // System.out.println(date1);
      //       InputStream is = new ByteArrayInputStream(str.getBytes());
      //       String objectname = "distributed/can1/" + date1 + "-" +(index++)+ ".txt";
      //       try {
      //         client.putObject(bucket, objectname,
      //             is, str.length(), "text/plain");
      //         // queue.poll();
      //       } catch (Exception e) {
      //         // TODO Auto-generated catch block
      //         queue.offer(x);
      //         e.printStackTrace();
      //       }
      //       // is.close();
      //     }
  
      //   });
  
      // }
      // try{
      //   Thread.sleep(100);
      // }catch(InterruptedException e){
      //   e.printStackTrace();
      // }
    // }
  }

  public static void upload(String name, String filepath) throws Exception {
    if (client == null) {
      init();
    }
    boolean isExist = client.bucketExists(bucket);
    if (!isExist) {
      client.makeBucket(bucket);

    }
    client.putObject(bucket, name, filepath);
    // LOG.info("[+]file "+name+" has uploaded");
  }

  public static void movetouploaded(FileUnit fileUnit) {
    String p = fileUnit.getFile().getPath().replace("local", "uploaded");

    File path = new File(p);
    if (!path.exists()) {
      path.mkdirs();
    }

    fileUnit.getFile().renameTo(new File(p + "/" + fileUnit.getFile().getName()));
  }

  public static void deletefile(FileUnit fileUnit) {
    if (fileUnit.getFile().exists()) {
      fileUnit.getFile().delete();
    }
  }
}